package com.aaron.kjviewutils.carte;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.RecycleViewDividerForList;
import com.aaron.kjviewutils.eventBus.BundleEventMsg;
import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.github.ybq.android.spinkit.Style;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.yyydjk.library.DropDownMenu;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者：Aaron on 2017/2/21 11:38
 * 邮箱：kaijin.fang@edianniu.com
 */
public class CarteActivity extends BaseActivity implements PullLoadMoreRecyclerView.PullLoadMoreListener {

    @Bind(R.id.carteToolBar)
    Toolbar carteToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.dropDownMenu)
    DropDownMenu dropDownMenu;
    @Bind(R.id.footRecycler)
    PullLoadMoreRecyclerView footRecycler;

    private CarteService carteService;
    private RecyclerView mRecyclerView;
    private Call<ResponseBody> call;
    private  Call<CarteDetailBean> reflushCall;
    private  Call<CarteDetailBean> loadMoreCall;
    private List<CarteBean> cartes;
    private List<String> carteTags;
    private List<View> popupViews;
    private int curPage = 1;
    private int pageSize = 10;
    private List<CarteDetailBean.CarteDetailInfo.CarteDetailInner> datas;
    private CarteRecyclerViewAdapter adapter;
    private String cid;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        if (dropDownMenu.isShowing()) {
            dropDownMenu.closeMenu();
        }
        else
        {
            //关闭
            closeSelf(CarteActivity.this);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_carte);
        ButterKnife.bind(this);
        initTitle();
        initContent();
        initRecyclerView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_CARTE:
            {
                Bundle bundle = msg.getBundle();
                cid = bundle.getString("cid");
                if(null!=retrofit)
                {
                    carteService = retrofit.create(CarteService.class);
                    footRecycler.refresh();
                }
            }
            break;
            default:
                break;
        }
    }

    private void initRecyclerView()
    {
        mRecyclerView = footRecycler.getRecyclerView();
        datas = new ArrayList<CarteDetailBean.CarteDetailInfo.CarteDetailInner>();
        //这里用线性显示 类似于listview
        adapter = new CarteRecyclerViewAdapter(CarteActivity.this, datas);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.addItemDecoration(new RecycleViewDividerForList(
                CarteActivity.this, LinearLayoutManager.HORIZONTAL));
        //显示下拉刷新
        footRecycler.setRefreshing(true);
        //设置上拉刷新文字
        footRecycler.setFooterViewBackgroundColor(android.R.color.transparent);
        //设置上拉刷新文字颜色
        //mPullLoadMoreRecyclerView.setFooterViewTextColor(R.color.white);
        //设置加载更多背景色
        //mPullLoadMoreRecyclerView.setFooterViewBackgroundColor(R.color.colorBackground);
        footRecycler.setLinearLayout();

        footRecycler.setOnPullLoadMoreListener(this);
        footRecycler.setAdapter(adapter);
        footRecycler.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case LOAD_DATA_CARTE:
            {
                mHandler.postDelayed(runnableLoadCarte, 500);
            }
            break;
            case LOAD_DATA_CARTE_UI:
            {
                //加载下拉组件

                if(null!=cartes&&!cartes.isEmpty())
                {
                    carteTags = new ArrayList<String>();
                    popupViews = new ArrayList<>();
                    int size = cartes.size();
                    for(int i=0; i<size; i++)
                    {
                        final CarteBean carteInfo = cartes.get(i);
                        final int index = i;
                        carteTags.add(carteInfo.categoryInfo.name.substring(0, 3));
                        final CarteAapter dapter = new CarteAapter(CarteActivity.this, carteInfo.childs);
                        RecyclerView recyclerView = new RecyclerView(this);
                        recyclerView.setLayoutManager(new LinearLayoutManager(CarteActivity.this));
                        recyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
                        recyclerView.setLayoutParams(new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, RecyclerView.LayoutParams.MATCH_PARENT));
                        recyclerView.setAdapter(dapter);
                        dapter.setmOnItemClickListener(new CarteAapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                dropDownMenu.setTabText(position == -1 ? carteTags.get(position) : carteInfo.childs.get(position).categoryInfo.name);
                                dropDownMenu.closeMenu();
                                Bundle bundle = new Bundle();
                                bundle.putString("cid", position == -1 ? String.valueOf(0) : carteInfo.childs.get(position).categoryInfo.ctgId);
                                eventBus.post(new BundleEventMsg(BundleEventMsg.EventBusType.BUNDLE_CARTE, bundle));
                            }
                        });
                        popupViews.add(recyclerView);
                    }
                    LinearLayout contentView = new LinearLayout(this);
                    contentView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, LinearLayout.LayoutParams.MATCH_PARENT));
                    dropDownMenu.setDropDownMenu(carteTags, popupViews, contentView);
                }
            }
            break;
            default:
                break;
        }
    }

    Runnable runnableLoadCarte = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(carteToolBar, Gravity.CENTER, 0, 0);
            }
            //获取菜单数据
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            carteService = retrofit.create(CarteService.class);
            call = carteService.obtainCartes();
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (null != progress) {
                        progress.dismissView();
                    }
                    try {
                        String source = response.body().string();
                        if (TextUtils.isEmpty(source)) {
                            showMsg("获取菜单信息失败");
                        } else {
                            JSONObject object = new JSONObject(source);
                            JsonParser parser = new JsonParser();
                            JsonObject json01 = parser.parse(source).getAsJsonObject();
                            JsonObject json02 = json01.getAsJsonObject("result");
                            JsonArray json03 = json02.getAsJsonArray("childs");
                            Gson gson = new Gson();
                            cartes = new ArrayList<CarteBean>();
                            for (int i = 0; i < json03.size(); i++)
                            {
                                JsonElement j = json03.get(i);
                                CarteBean carte=gson.fromJson(j, new TypeToken<CarteBean>() {
                                }.getType());
                                cartes.add(carte);
                            }
                            if ("200".equals(object.getString("retCode"))) {
                                eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.LOAD_DATA_CARTE_UI));
                            } else {
                                showMsg(object.getString("msg"));
                            }
                        }
                    } catch (IOException e) {
                        showMsg("获取菜单信息失败");
                    } catch (JSONException e) {
                        showMsg("获取菜单信息失败");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if (null != progress) {
                        progress.dismissView();
                    }
                    showMsg("获取菜单信息失败");
                }
            });
        }
    };

    private void initContent()
    {
        eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.LOAD_DATA_CARTE));
    }

    private void initTitle()
    {
        carteToolBar.setTitle("");
        barTitle.setText("菜谱大全");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        carteToolBar.setNavigationIcon(null);
    }

    Runnable runnableReflush = new Runnable() {
        @Override
        public void run() {
            if(null!=carteService)
            {
                if(1!=curPage)
                {
                    curPage = 1;
                }
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("cid", (TextUtils.isEmpty(cid))?"0010001034":cid);
                params.put("page", curPage);
                params.put("size", pageSize);
                reflushCall = carteService.obtainFootByMenu(params);
                reflushCall.enqueue(new Callback<CarteDetailBean>() {
                    @Override
                    public void onResponse(Call<CarteDetailBean> call, Response<CarteDetailBean> response) {
                        reflushCall.cancel();
                        footRecycler.setPullLoadMoreCompleted();
                        CarteDetailBean data = response.body();
                        if("200".equals(data.retCode))
                        {
                            List<CarteDetailBean.CarteDetailInfo.CarteDetailInner> results = data.result.list;
                            if(null!=results&&!results.isEmpty())
                            {
                                datas.clear();
                                datas.addAll(results);
                                adapter.notifyDataSetChanged();
                            }
                            else
                            {
                                showMsg("获取数据失败");
                            }
                        }
                        else
                        {
                            showMsg(data.msg);
                        }
                    }

                    @Override
                    public void onFailure(Call<CarteDetailBean> call, Throwable t) {
                        reflushCall.cancel();
                        footRecycler.setPullLoadMoreCompleted();
                        showMsg("获取数据失败");
                    }
                });
            }
        }
    };

    Runnable runnableLoadMore = new Runnable() {
        @Override
        public void run() {
            if(null!=carteService)
            {
                curPage=curPage+1;
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("cid", (TextUtils.isEmpty(cid))?"0010001034":cid);
                params.put("page", curPage);
                params.put("size", pageSize);
                loadMoreCall = carteService.obtainFootByMenu(params);
                loadMoreCall.enqueue(new Callback<CarteDetailBean>() {
                    @Override
                    public void onResponse(Call<CarteDetailBean> call, Response<CarteDetailBean> response) {
                        loadMoreCall.cancel();
                        footRecycler.setPullLoadMoreCompleted();
                        CarteDetailBean data = response.body();
                        if("200".equals(data.retCode))
                        {
                            List<CarteDetailBean.CarteDetailInfo.CarteDetailInner> results = data.result.list;
                            if(null!=results&&!results.isEmpty())
                            {
                                datas.addAll(results);
                                adapter.notifyDataSetChanged();
                            }
                            else
                            {
                                showMsg("获取数据失败");
                            }
                        }
                        else
                        {
                            showMsg(data.msg);
                        }
                    }

                    @Override
                    public void onFailure(Call<CarteDetailBean> call, Throwable t) {
                        reflushCall.cancel();
                        footRecycler.setPullLoadMoreCompleted();
                        showMsg("获取数据失败");
                    }
                });
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            if (dropDownMenu.isShowing()) {
                dropDownMenu.closeMenu();
                return true;
            }
            else
            {
                //关闭
                closeSelf(CarteActivity.this);
                return super.onKeyDown(keyCode, event);
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadCarte);
            mHandler.removeCallbacks(runnableReflush);
            mHandler.removeCallbacks(runnableLoadMore);
        }
        if(null!=footRecycler)
        {
            footRecycler.cancelLongPress();
        }
        if(null!=call)
        {
            call.cancel();
        }
        if(null!=reflushCall)
        {
            reflushCall.cancel();
        }
        if(null!=loadMoreCall)
        {
            loadMoreCall.cancel();
        }
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(runnableReflush, 1000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(runnableLoadMore, 1000);
    }
}
